package com.bbcare.followup.plat.controller;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.comm.*;
import com.bbcare.followup.plat.service.IHisService;


/**
 * 万能HIS对接。
 */
@Controller
@RequestMapping("/service/his")
public class WNHisController {
    private final static Logger logger = Logger.getLogger(WNHisController.class);

    @Autowired
    private IHisService hisService;

    /**
     * 查询住院患者列表。
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/queryInPatientList")
    public ResultModel<Map<String, Object>> queryPatientList(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryInPatientList() begin.");
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String queryUsername  = jsonData.getString("username");
        final String queryPhone = jsonData.getString("phone");
        int page = jsonData.getIntValue("page");    //页号从1开始。
        int rows = jsonData.getIntValue("rows");    //每页记录数量。
        page = (page == 0) ? 1 : page;
        rows = (rows == 0) ? 20 : rows;
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId   = (String) sessionMap.get("tenantId");

        Map<String, Object> paraMap = new HashMap<String, Object>();
        paraMap.put("tenantId", tenantId);
        paraMap.put("username", (null==queryUsername)?"":queryUsername);
        paraMap.put("phone",    (null==queryPhone)?"":queryPhone);
        paraMap.put("start", (page - 1) * rows);
        paraMap.put("end",      rows);
        Map<String,Object> retMap   = hisService.queryByCondition(paraMap);
        final Integer total = (Integer)retMap.get("total");
        final List<Map<String,Object>> rowlist  = (List<Map<String,Object>>)retMap.get("rowlist");
        retMap.put("rows",  rowlist);
        retMap.put("total", total);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    /**
     * 查询住院患者详情。
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/queryInPatientInfo")
    public ResultModel<Map<String, Object>> queryInPatientInfo(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryInPatientInfo()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String patientId  = jsonData.getString("patientId");
        if (StringUtils.isEmpty(patientId) || StringUtils.isBlank(patientId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入patientId或值为空！"));
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId = (String) sessionMap.get("tenantId");

        Map<String, Object> retMap = hisService.queryInPatientInfo(tenantId, patientId);
        return new ResultModel<Map<String, Object>>(retMap);
    }

    /**
     * 查询患者住院历史。
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/queryInPatientHistory")
    public ResultModel<Map<String, Object>> queryInPatientHistory(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryInPatientHistory()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String patientId  = jsonData.getString("patientId");
        if (StringUtils.isEmpty(patientId) || StringUtils.isBlank(patientId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入patientId或值为空！"));
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId = (String) sessionMap.get("tenantId");

        Map<String, Object> retMap = new HashMap<String, Object>();
        List<Map<String,Object>> inpatientHistoryList   = hisService.queryInPatientHisList(tenantId, patientId);
        int total = 0;
        if (null != inpatientHistoryList) {
            total = inpatientHistoryList.size();
        }
        retMap.put("rows", inpatientHistoryList);
        retMap.put("total", total);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    /**
     * 保存随访系统患者ID和HIS系统ID之间的映射。
     * @return "success", "fail".
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/saveFollowupidHisid")
    public ResultModel<String> saveFollowupIdAndHisId(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++saveFollowupIdAndHisId()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String followupId = jsonData.getString("followupId");
        if (StringUtils.isEmpty(followupId) || StringUtils.isBlank(followupId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入patientId或值为空！"));
        }
        final String hisId  = jsonData.getString("hisId");
        if (StringUtils.isEmpty(hisId) || StringUtils.isBlank(hisId)) {
            //throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入hisId或值为空！"));
            //如果没有hisid参数，说明是系统内部建档，和HIS系统无关。
            return new ResultModel("fail");
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId = (String) sessionMap.get("tenantId");
        int saveResult = hisService.saveIdMapper(tenantId, followupId, hisId);
        if (1==saveResult)  {
            return new ResultModel("success");
        } else {
            return new ResultModel("fail");
        }
    }

    /**
     * 查询患者医疗文书链接。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/queryDocuLink")
    public ResultModel<Map<String, Object>> queryDocuLink(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++queryDocuLink()----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        final String followupId  = jsonData.getString("followupId");
        if (StringUtils.isEmpty(followupId) || StringUtils.isBlank(followupId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入patientId或值为空！"));
        }

        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        final String tenantId = (String) sessionMap.get("tenantId");
        final String docuLink = hisService.queryDocuLink(tenantId, followupId);
        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("docuLink", docuLink);
        return new ResultModel<Map<String, Object>>(retMap);
    }
}
